<template>
    <div class="page-content">
        <div class="header">
            <h3>训练场</h3>
        </div>
        <!-- 表格菜单 -->
        <el-tabs v-model="tableLayout" class="demo-tabs" @tab-change="handleClick" style="margin-top: 20px">
            <el-tab-pane label="驾校管理" name="1"> </el-tab-pane>
            <el-tab-pane label="车型分类" name="2"> </el-tab-pane>
            <el-tab-pane label="报名地点" name="3"> </el-tab-pane>
            <el-tab-pane label="招生员" name="4"> </el-tab-pane>
            <el-tab-pane label="教练管理" name="5"> </el-tab-pane>
            <el-tab-pane label="训练场" name="6"> </el-tab-pane>
        </el-tabs>
        <!-- 表格菜单 -->
        <el-row style="margin-top: 20px;">
            <div style="width: 12px"></div>
            <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
                <el-button @click="showDialog('add')" v-ripple>新增训练场</el-button>
            </el-col>
        </el-row>

        <art-table :data="tableData" :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize"
            :total="pageTotal" @current-change="currentChange" @size-change="sizeChange">
            <template #default>
                <el-table-column label="ID" prop="id" width="55" align="center" />
                <el-table-column label="排序" prop="sort" align="center" />
                <el-table-column label="训练场名称" prop="name" align="center" />
                <el-table-column label="训练场地址" prop="address" align="center" />
                <el-table-column label="训练场照片" prop="img" align="center">
                    <template #default="scope">
                        <img class="xlcImg" :src="scope.row.img" v-if="scope.row.img" />
                    </template>
                </el-table-column>
                <el-table-column #default="scope" label="启用状态" align="center">
                    <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
                        @click="editStatus(scope.row.id, scope.row.status)" />
                </el-table-column>
                <el-table-column label="创建时间：" prop="createTime" align="center">
                    <template #default="scope">
                        {{ formatDate(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="150px" align="center">
                    <template #default="scope">
                        <button-table type="edit" @click="buttonMoreClick(scope.row)" />
                        <button-table type="delete" @click="deleteRole(scope.row.id)" />
                    </template>
                </el-table-column>
            </template>
        </art-table>

        <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增训练场' : '编辑训练场'" width="30%"
            :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="排序" prop="sort">
                    <el-input v-model="form.sort" :rows="3" />
                </el-form-item>
                <el-form-item label="训练场名称" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="训练场地址" prop="address">
                    <el-input v-model="form.address" />
                </el-form-item>
                <el-form-item label="地图定位">
                    <el-row :gutter="12">
                        <el-col :span="6"><el-button @click="showMapDialog = true">选择经纬度</el-button></el-col>
                        <el-col :span="8"><el-input v-model="form.latitude"></el-input></el-col>
                        <el-col :span="8"><el-input v-model="form.longitude"></el-input></el-col>
                    </el-row>
                </el-form-item>
                <el-form-item label="训练场照片" prop="img">
                    <el-input v-model="form.img" style="display: none"></el-input>
                    <div class="avatar-uploader" @click="showImageChooseDialog = true">
                        <el-image v-if="form.img" :src="form.img" class="avatar" fit="contain"></el-image>
                        <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                                <Plus />
                            </el-icon></i>
                        <div v-if="form.img" class="mask">替换</div>
                        <el-icon v-if="form.img" class="del-image" :size="20" @click.stop="handleDelImg">
                            <CircleCloseFilled />
                        </el-icon>
                    </div>
                </el-form-item>
                <el-form-item label="启用状态" prop="status">
                    <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
                </div>
            </template>
        </el-dialog>
        <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
            :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
            :operationType="false"></image-selected-dialog>

        <map-dialog v-if="showMapDialog" :show-map-dialog-visible="showMapDialog" @cancel="showMapDialog = false"
            @location-selected="selectMapAddress"></map-dialog>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { trainingGround, AddTrainingGround, EditTrainingGround, DelTrainingGround } from '@/api/driverSchoolApi'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'
import MapDialog from '@/views/drivingschool/components/MapSelectorDialog.vue'

const dialogVisible = ref(false)
const tableLayout = ref('6')
const showMapDialog = ref(false)

const formRef = ref<FormInstance>()
const router = useRouter() // 使用useRouter获取路由实例

const rules = reactive<FormRules>({
    typename: [
        { required: true, message: '请输入报名名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    sortOrder: [{ required: true, message: '请输入正确排序', trigger: 'blur' }],
    img: [{ required: true, message: '请选择训练场照片', trigger: 'change' }]
})
const tableLoading = ref(false)
const form = reactive({
    id: Number(''),
    sort: 1,
    name: '',
    address: '',
    img: '',
    status: 1,
    latitude: '',
    longitude: ''
})

const showImageChooseDialog = ref(false)
const selectImageSingle = ref(true)
const handleCloseImageDialog = (value: any) => {
    if (value && value.fileUrl) { form.img = value.fileUrl }
    showImageChooseDialog.value = false
}


const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
async function getData() {
    try {
        tableLoading.value = true

        const { code, data } = await trainingGround({
            pageNum: pageNum.value,
            pageSize: pageSize.value
        })
        if (code === '00000') {
            tableData.value = data.list
            pageTotal.value = data.total
        }
    } catch (e) {
    } finally {
        tableLoading.value = false
    }
}
const currentChange = (val: number) => {
    pageNum.value = val
    getData()
}

const sizeChange = (val: number) => {
    pageSize.value = val
    pageNum.value = 1
    getData()
}
const dialogType = ref('add')

const showDialog = (type: string, row?: any) => {
    dialogVisible.value = true
    dialogType.value = type
    if (type === 'edit' && row) {
        form.id = row.id
    } else {
        form.id = Number('')
        form.sort = 1
        form.name = ''
        form.address = ''
        form.img = ''
        form.status = 1
        form.latitude = ''
        form.longitude = ''
    }
}

const buttonMoreClick = (row: any) => {
    showDialog('edit', row)
    Object.assign(form, {
        name: row.name,
        sort: row.sort,
        address: row.address,
        img: row.img,
        latitude: row.latitude,
        longitude: row.longitude,
    })
}

const deleteRole = (id: number) => {
    ElMessageBox.confirm('确定删除该训练场吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
    }).then(async () => {
        const res = await DelTrainingGround(id)
        if (res.code === '00000') {
            getData()
            ElMessage.success('删除成功')
        }
    })
}

const handleSubmit = async (formEl: FormInstance | undefined) => {

    if (!formEl) return

    await formEl.validate(async (valid) => {
        if (valid) {
            const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
            const isAdd = dialogType.value === 'add'
            const params = {
                sort: form.sort,
                name: form.name,
                address: form.address,
                img: form.img,
                status: form.status,
                latitude: form.latitude,
                longitude: form.longitude
            }
            let res
            if (isAdd) {
                res = await AddTrainingGround(params)
            } else {
                res = await EditTrainingGround({ ...params, id: form.id })
            }
            if (res.code === '00000') {
                ElMessage.success(message)
                dialogVisible.value = false
                getData()
            }
        }
    })
}

async function editStatus(id: any, status: any) {
    try {
        const res = await EditTrainingGround({
            status,
            id
        })
        if (res.code === '00000') {
            ElMessage.success('修改成功')
        }
    } catch (e) {
    } finally {
        await getData()
    }
}

const formatDate = (date: string) => {
    return new Date(date)
        .toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        })
        .replace(/\//g, '-')
}


const handleClick = (e: any) => {
    if (e === '1') {
        setTimeout(() => {
            router.push('/drivingschool/DrivingschoolManagement')
        }, 0)
    } else if (e === '2') {
        setTimeout(() => {
            router.push('/drivingschool/question_bank_type')
        }, 0)
    } else if (e === '3') {
        setTimeout(() => {
            router.push('/drivingschool/question_bank_type_baoming')
        }, 0)
    } else if (e === '4') {
        setTimeout(() => {
            router.push('/drivingschool/question_bank_type_zhaosheng')
        }, 0)
    } else if (e === '5') {
        setTimeout(() => {
            router.push('/drivingschool/question_bank_type_jiaolian')
        }, 0)
    } else if (e === '6') {
        setTimeout(() => {
            router.push('/drivingschool/question_bank_type_xunlianchang')
        }, 0)
    }
}
const handleDelImg = () => {
    form.img = ''
}

function selectMapAddress(value: any) {
    form.latitude = value.lat
    form.longitude = value.lng
    showMapDialog.value = false
}

onMounted(() => {
    getData()
})
</script>

<style lang="scss" scoped>
.page-content {
    .svg-icon {
        width: 1.8em;
        height: 1.8em;
        overflow: hidden;
        vertical-align: -8px;
        fill: currentcolor;
    }
}

.tableimg {
    width: 8rem;
    height: 4.5rem;
    border-radius: 0.5rem;
    overflow: hidden;
}

.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;

    .mask {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 24px;
        background-color: rgba(0, 0, 0, 0.6);
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.3s ease;
        color: #fff;
        font-size: 12px;
    }

    .del-image {
        display: none;
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
        color: #8c939d;
    }

    &:hover .mask {
        opacity: 1;
    }

    &:hover .del-image {
        display: block;
    }
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
}

.avatar {
    width: 150px;
    height: 150px;
    display: block;
}

.xlcImg {
    width: 50px;
    height: 50px;
}
</style>